import struct
import time

from serial import Serial

port = "COM16"



class CMD:
    Info = 0x02
    Version = 0x03
    Test = 0x04

    Read = 0xA1
    Write = 0xB1
    Erase = 0xC1

    Lock = 0xD1
    Unlock = 0xD2

    # 设置地址
    SetAddress = 0xE1
    # 设置缓存
    SetBuffer = 0xE2
    # 设置写入字节长度 2字节 1字节、64、128、256、512
    SetWriteBuffer = 0xE3
    # 设置读写16字节顺序 MD默认1 高位+低位。8位模式0 低位+高位
    SetMdMode = 0xE4


def doRead():
    with Serial(baudrate = 115200, timeout = 2, write_timeout = 2) as s:

        def sendCMD(cmd, length=0, data=0):
            buffer = bytearray()
            buffer.extend(struct.pack("B", cmd))
            if length == 1:
                buffer.extend(struct.pack("B", data))
            elif length == 2:
                buffer.extend(struct.pack(">H", data))
            elif length == 4:
                buffer.extend(struct.pack(">I", data))
            s.write(buffer)
            s.flush()

        s.port = port
        s.open()
        if s.is_open:

            # sendCMD(CMD.SetBuffer, 4, 128)
            # res = s.readline()
            # res = res[0:len(res)-2] if len(res)>2 else res
            # print("设置缓存128:{}".format(res))


            address = 0;
            length = 8*1024*1024
            file = "d:/gba.gba"


            sendCMD(CMD.SetAddress, 4, 0x0)
            res = s.readline()
            res = res[0:len(res)-2] if len(res) > 2 else res
            print("设置地址:{}".format(res))


            startTime = time.time()
            with open(file,'wb') as f:
                while address < length:
                    print("{}".format("%08X" % address))
                    # 设置 wsc
                    sendCMD(0x20)
                    # res = s.readline()
                    res = s.read(64)
                    if address < 8192:
                        bs = []
                        print("数据: {}".format(len(res)))
                        for i in range(len(res)):
                            bs.append(('%02X' % res[i]))
                        print("{}".format(" ".join(bs)))
                        print("{}".format("".join(bs)))
                    f.write(res)
                    # for i in range(128):
                    #     file_buffer.append(res[i])
                    address += 64

            endTime = time.time()
            print(str("读取耗时: {}".format('%.2f' % (endTime - startTime))))


    s.close()


def doReadID():
    with Serial(baudrate = 115200, timeout = 2, write_timeout = 2) as s:

        def sendCMD(cmd, length=0, data=0):
            buffer = bytearray()
            buffer.extend(struct.pack("B", cmd))
            if length == 1:
                buffer.extend(struct.pack("B", data))
            elif length == 2:
                buffer.extend(struct.pack(">H", data))
            elif length == 4:
                buffer.extend(struct.pack(">I", data))
            s.write(buffer)
            s.flush()

        s.port = port
        s.open()
        if s.is_open:

            sendCMD(CMD.SetAddress, 4, 0x0)
            res = s.readline()
            res = res[0:len(res)-2] if len(res) > 2 else res
            print("设置地址:{}".format(res))

            # 读取芯片ID
            sendCMD(0x21)
            # res = s.readline()
            res = s.read(2)
            bs = []
            print("数据: {}".format(len(res)))
            for i in range(len(res)):
                bs.append(('%02X' % res[i]))
            print("{}".format(" ".join(bs)))
            print("{}".format("".join(bs)))

            print("厂家: {}".format('%02X' % res[0]))
            print("型号: {}".format('%02X' % res[1]))

            changjias = {
                0xc2: "MXIC MX29",
                0x01: "Infineon S29",
                0xbf: "MicroChip SST39",

            }

            if res[0] in changjias:
                print("{}".format(changjias[res[0]]))

    s.close()



if __name__ == '__main__':
    # doRead()
    doReadID()
